#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SeqListInit(SeqList* ps)
{
	assert(ps);

	ps->a = (SLDateType*)malloc(sizeof(SLDateType)*CAPACI_MAX);
	if (NULL == ps->a)
	{
		printf("malloc fail");
		return;
	}

	ps->size = 0;
	ps->capacity = CAPACI_MAX;
}

void SeqListDestroy(SeqList* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SeqListPrint(SeqList* ps)
{
	assert(ps);

	int i = 0;
	for (i = 0; i < (ps->size); i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

int SeqListFind(SeqList* ps, SLDateType x)
{
	assert(ps);

	int i = 0;
	for (i = 0; i < (ps->size); i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}

	return -1;
}

void SeqListCapCheck(SeqList* ps)
{
	assert(ps);

	if (ps->size == ps->capacity)
	{
		SLDateType* tmp = (SLDateType*)realloc(ps->a, sizeof(SLDateType) * (ps->capacity) * 2); 
		if (NULL == tmp)
		{
			printf("realloc fail");
			return;
		}
		ps->a = tmp;
		ps->capacity *= 2;
	}
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
	assert(ps);

	SeqListCapCheck(ps);

	ps->a[ps->size] = x;
	(ps->size)++;
}

void SeqListPushFront(SeqList* ps, SLDateType x)
{
	assert(ps);

	SeqListCapCheck(ps);

	int end = ps->size++;
	while (end)
	{
		ps->a[end] = ps->a[end - 1];
		end--;
	}
	ps->a[end] = x;
}

void SeqListPopFront(SeqList* ps)
{
	assert(ps);

	int tail = 0;
	while (tail != ps->size)
	{
		ps->a[tail] = ps->a[tail + 1];
		tail++;
	}

	ps->a[tail] = 0;
	ps->size--;
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps);

	ps->a[ps->size-1] = 0;
	ps->size--;
}

void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	SeqListCapCheck(ps);

	int end = ps->size;
	while (end != pos)
	{
		ps->a[end] = ps->a[end - 1];
		end--;
	}

	ps->a[end] = x;
	ps->size++;
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	ps->a[pos] = 0;

	int end = ps->size - 1;
	while (pos != end)
	{
		ps->a[pos] = ps->a[pos + 1];
		pos++;
	}

	ps->size--;
	ps->a[ps->size] = 0;
}